/* eslint-disable max-len */
<template>
  <customContainer ref="mainConfig" :config="config" />
  <div>
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title">
      <el-form
        ref="form1"
        :model="form"
        :rules="rules"
        inline
        label-width="110px"
      >
        <el-form-item label="服务商" prop="providerServiceCode">
          <el-select
            v-model="form.providerServiceCode"
            filterable
            clearable
            style="width: 225px;"
          >
            <el-option
              v-for="dict in dicts[DictDirection.服务商]"
              :key="dict.providerServiceCode"
              :label="dict.serviceSimpleName"
              :value="dict.providerServiceCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务渠道" prop="serviceChannelCode">
          <el-select
            v-model="form.serviceChannelCode"
            filterable
            clearable
            style="width: 225px;"
          >
            <el-option
              v-for="dict in dicts[DictDirection.服务渠道]"
              :key="dict.id"
              :label="dict.channelChName"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提单号：" prop="ladingNo">
          <el-input v-model.trim="form.ladingNo" style="width: 225px;"></el-input>
        </el-form-item>
        <el-form-item v-if="form.transportType == 1" label="柜型" prop="cabinetType">
          <el-select
            v-model="form.cabinetType"
            filterable
            clearable
            style="width: 225px;"
          >
            <el-option
              v-for="dict in dicts[DictDirection.柜子型号]"
              :key="dict.id"
              :label="dict.cabinetType"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.transportType == 1" label="箱号：" prop="caseNo">
          <el-input
            v-model="form.caseNo"
            style="width: 225px;"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item v-if="form.transportType == 1" label="封号：" prop="sealNo">
          <el-input
            v-model="form.sealNo"
      
            style="width: 225px;"

            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="航次/航班：" prop="voyageNo">
          <el-input
            v-model="form.voyageNo"
            style="width: 225px;"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="运输类型：" prop="transportType">
          <el-select
            v-model="form.transportType"
            style="width: 225px;"
            filterable
            disabled
            clearable
          >
            <el-option
              v-for="dict in dicts[DictDirection.运输类型]"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="船/航空公司" prop="transportName">
          <el-input
            v-model="form.transportName"
            style="width: 225px;"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="目的港：" prop="portDestination">
          <el-input
            v-model="form.portDestination" 
            style="width: 225px;"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item :label="queryParams.transportType == 2 ? '预计起飞日' : '预计开船日'" prop="expectedSailingDate">
          <el-date-picker
            v-model="form.expectedSailingDate"
            style="width: 225px;"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="预计到达：" prop="expectedArrivalDate">
          <el-date-picker
            v-model="form.expectedArrivalDate"
            style="width: 225px;"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="装柜地点：" prop="loadingLocation">
          <el-select
            v-model="form.loadingLocation"
            style="width: 225px;"
            filterable
           
            clearable
          >
            <el-option
              v-for="dict in dicts[DictDirection.收货站点]"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.transportType == 1" label="报关行：" prop="customsLine">
          <el-input
            v-model="form.customsLine"          
            style="width: 225px;"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item v-if="form.transportType == 1" label="拖车行：" prop="trailerLine">
          <el-input
            v-model="form.trailerLine"
            style="width: 225px;"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remarks">
          <el-input
            v-model="form.remarks"
            style="width: 225px;"
            type="textarea"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button @click="editCancel">取消</el-button>
      </div>
    </el-dialog>
    <!-- 撤销签出 -->
    <el-dialog
      v-model="open1"
      :close-on-click-modal="false"
      width="30%"
      title="撤销"
    >
      <el-form
        ref="form2"
        :model="revokeForm"
        :rules="revokeRules"
        label-width="100px"
      >
        <el-form-item label="柜号" prop="ladingNo">
          <el-input
            v-model="revokeForm.ladingNo"
            type="textarea"
            readonly
            autosize
            clearable
            style="width: 220px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="撤销人" prop="nickName">
          <el-input v-model="revokeForm.nickName" readonly style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="revokeForm.remark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 10 }"
            style="width: 220px;"
          ></el-input>
        </el-form-item>
      
        <div class="dialog-footer">
          <el-button @click="cancle1">取 消</el-button>
          <el-button type="primary" @click="revokeSubmit">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      v-model="open2"
      :close-on-click-modal="false"
      width="30%"
      :title="title2"
    >
      <el-form
        ref="queryForm"
        :inline="true"
        :model="form3"
        label-width="110px"
      >
        <el-form-item
          label="操作时间"
          prop="operationTime"
          :rules="{
            required: true,
            message: '请输入操作时间',
            trigger: 'blur',
          }"
        >
          <el-date-picker
            v-model="form3.operationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
    
        <div class="dialog-footer">
          <el-button @click="cancle2">取 消</el-button>
          <el-button type="primary" @click="sumit2">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog v-model="open5" title="柜子信息" :before-close="cancle5">
      <el-table
        v-loading="loading5"
        border
        height="200px"
        :data="tableList1"
      >
        <el-table-column
          label="客户单号"
          align="center"
          prop="waybillNo"
          min-width="150"
        ></el-table-column>
        <el-table-column
          label="状态"
          align="center"
          prop="splittingStatus"
          min-width="100"
        ></el-table-column>
        <el-table-column
          label="转单号"
          align="center"
          prop="transferOrderNo"
          min-width="100"
        ></el-table-column>
        <el-table-column
          label="类型"
          align="center"
          prop="quotationType"
          min-width="100"
        ></el-table-column>
        <el-table-column
          label="销售产品"
          align="center"
          prop="marketProducts"
          min-width="100"
        ></el-table-column>
        <el-table-column
          label="总实重"
          align="center"
          prop="receivingTotalWeight"
          min-width="150"
        ></el-table-column>
        <el-table-column
          label="系统订单号"
          align="center"
          prop="orderNo"
          min-width="150"
        ></el-table-column>
      </el-table>
      <div>
        <el-button loading type="primary" @click="sumit5">确定</el-button>
        <el-button type="info" @click="cancle5">取消</el-button>
      </div>
    </el-dialog>
    <!-- 提柜 -->
    <el-dialog v-model="open4" :close-on-click-modal="false" :title="title4">
      <el-form
        ref="popoverForms"
        :model="popoverForm"
        label-width="180px"
        inline
      >
        <el-form-item prop="date" :label="popoverForm.title" :rules="[{ required: true, message: '请选择日期', trigger: ['blur'] }]">
          <el-date-picker
            v-model="popoverForm.date"
            clearable
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="cancle4">取 消</el-button>
        <el-button type="primary" :loading="btnLoading4" @click="sumit4">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 清关 -->
    <el-dialog
      v-model="open3"
      :close-on-click-modal="false"
      :title="title3"
      append-to-body
    >
      <el-form
        ref="forms4"
        :model="form4"
        :rules="rules2"
        inline
        label-width="100px"
      >
        <el-form-item label="FDA" prop="FDA">
          <el-input v-model.number="form4.FDA" style="width: 182px !important;"></el-input>
        </el-form-item>
        <el-form-item label="清关" prop="清关">
          <el-input v-model.number="form4.清关" style="width: 182px !important;"></el-input>
        </el-form-item>
        <el-form-item label="ISF" prop="ISF">
          <el-input v-model.number="form4.ISF" style="width: 182px !important;"></el-input>
        </el-form-item>
        <el-form-item label="税额" prop="税额">
          <el-input v-model.number="form4.税额" style="width: 182px !important;"></el-input>
        </el-form-item>
        <el-form-item label="查验" prop="查验">
          <el-input v-model.number="form4.查验" style="width: 182px !important;"></el-input>
        </el-form-item>
        <el-form-item label="其他" prop="其他">
          <el-input v-model.number="form4.其他" style="width: 182px !important;"></el-input>
        </el-form-item>
        <el-form-item prop="clearanceTime" label="清关日期">
          <el-date-picker
            v-model="form4.clearanceTime"
            clearable
            size="small"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="datetime"
            placeholder="选择日期"
            style="width: 182px !important; margin-right: 10px;"
          ></el-date-picker>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="cancle2">取 消</el-button>
          <el-button type="primary" @click="sumit2">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- <el-dialog
      v-model="open6"
      :close-on-click-modal="false"
      title="清关费用详情"
      append-to-body
    >
      <el-table v-loading="loading6" :data="feesDetailsList" border>
        <el-table-column label="费用名称" prop="feeName" align="center"></el-table-column>
        <el-table-column label="金额" prop="amount" align="center"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" text @click="handleEditFeesDetail(scope.row)">编辑</el-button>
            <el-button type="primary" text @click="handleDeleteFeesDetail(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog> -->
  
    <Cabinet ref="cabRef" @refush="initData"></Cabinet>
    <zgEdit ref="zgEditRef" @refush="initData"></zgEdit>
    <mainInfo ref="mainInfoRef"></mainInfo>
    <PayName ref="payRef"></PayName>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineAsyncComponent, getCurrentInstance } from 'vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
// eslint-disable-next-line max-len
import { mergeOutList, delPackage, saveOrderArrivedTrack, domesticDeclaration, domesticInspection, domesticDomestically, foreignInspection, customsClearance, ladingOut, queryMergeLoadingOrderInfo, abroadClearanceReleased, submitOverseas, carryCabinet, submitUps } from '@/api/expressManager/outPutOrder'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import userStore from '@/store/modules/user'

const Cabinet = defineAsyncComponent(() => import('./components/cabinet.vue'))
const zgEdit = defineAsyncComponent(() => import('./components/zgEdit.vue'))
const mainInfo = defineAsyncComponent(() => import('./components/mainInfo.vue'))
const PayName = defineAsyncComponent(() => import('./components/PayName.vue'))
const dicts = useDicts()
const user = userStore()
const userName = user.user.nickName
const queryParams = ref({
  pageSize: 10,
  pageNum: 1,
  waybillNo: undefined,
  ladingNo: undefined,
  cabinetNo: undefined,
  orderNo: undefined,
  providerServiceCode: undefined,
  voyageNo: undefined,
  transportName: undefined,
  caseNo: undefined,
  status: undefined,
  transportType: 1,
})
const cabRef = ref(undefined)
const zgEditRef = ref(undefined)
const mainInfoRef = ref(undefined)
const payRef = ref(undefined)
dicts.setDicts(DictDirection.产品)
dicts.setDicts(DictDirection.服务商)
dicts.setDicts(DictDirection.服务渠道)
dicts.setDicts(DictDirection.柜子型号)
const single = ref(true),
  single2 = ref(true),
  multiple2 = ref(true),
  // 非多个禁用
  multiple = ref(true)
const mainConfig = ref(null)
const open = ref(false)
const open1 = ref(false)
const open2 = ref(false)
const open3 = ref(false)
const open4 = ref(false)
const open5 = ref(false)
const title = ref(null)
const title2 = ref(null)
const title3 = ref(null)
const title4 = ref(null)
const loading5 = ref(false)
const btnloading = ref(false)

const tableList1 = ref([])

const form = ref({
  providerServiceCode: undefined,
  serviceChannelCode: undefined,
  ladingNo: undefined,
  transportType: 1,
  voyageNo: undefined,
  transportName: undefined,
  portDestination: undefined,
  expectedSailingDate: undefined,
  expectedArrivalDate: undefined,
  loadingLocation: undefined,
  customsLine: undefined,
  trailerLine: undefined,
  remarks: undefined,
  caseNo: undefined,
  sealNo: undefined,
  cabinetType: undefined,
  id: '',
  cabinetNo: '',
})
const revokeForm = ref({
  ladingNo: undefined,
  nickName: userName,
  remark: undefined,
})
const form3 = ref({
  operationTime: undefined,
})
const form4 = ref({
  FDA: undefined,
  清关: undefined,
  ISF: undefined,
  税额: undefined,
  查验: undefined,
  其他: undefined,
  clearanceTime: undefined,
})

const popoverForms = ref(undefined)
const { proxy } = getCurrentInstance() as any
const form1 = ref(undefined)
const form2 = ref(undefined)
const forms4 = ref(undefined),
  {
    appContext: {
      config: {
        globalProperties: { $validateForm, $download },
      },
    },
  } = getCurrentInstance()
const queryForm = ref(undefined)
const ruleBC = [{ required: true, message: '必填项未输入', trigger: ['blur', 'change'] }]
const ruleB = [{ required: true, message: '必填项未输入', trigger: 'blur' }]
const rules = {
  agent: ruleBC,
  serviceChannelCode: ruleBC,
  ladingNo: ruleB,
  cabinetType: ruleB,
  caseNo: ruleB,
  sealNo: ruleB,
  voyageNo: ruleB,
  transportType: ruleB,
  transportName: ruleB,
  portDestination: ruleB,
  expectedSailingDate: ruleB,
  expectedArrivalDate: ruleB,
  loadingLocation: ruleB,
  customsLine: ruleB,
  trailerLine: ruleB,
}
const rules2 = {
  FDA: [
    { required: true, message: '必填', trigger: 'blur' },
    // { type: "number", message: "该数据的值为数字", trigger: ["blur", "change"] },
  ],
  清关: [
    { required: true, message: '必填', trigger: 'blur' },
    // { type: "number", message: "该数据的值为数字", trigger: ["blur", "change"] },
  ],
  ISF: [
    { required: true, message: '必填', trigger: 'blur' },
    // { type: "number", message: "该数据的值为数字", trigger: ["blur", "change"] },
  ],
  税额: [
    { required: true, message: '必填', trigger: 'blur' },
    // { type: "number", message: "该数据的值为数字", trigger: ["blur", "change"] },
  ],
  查验: [
    { required: true, message: '必填', trigger: 'blur' },
    // { type: "number", message: "该数据的值为数字", trigger: ["blur", "change"] },
  ],
  clearanceTime: [{ required: true, message: '必填', trigger: ['blur', 'change'] }],
}
const revokeRules = {
  ladingNo: [{ required: true, message: '柜号不能为空', trigger: ['change', 'blur'] }],
  remark: [{ required: true, message: '备注不能为空', trigger: ['blur'] }],
}
// 查看详情
const handleRouterPush = (row: { [key: string]: any }) => {
  const data = {
    id: row.id,
    orderNo: row.orderNo,
    pageSize: 10,
    pageNum: 1,
  }
  console.log(row)
  
  mainInfoRef.value.rowss = row
  mainInfoRef.value.open = true
  mainInfoRef.value.title = '数据详情'
  mainInfoRef.value.idss = data
  mainInfoRef.value.loading = true
  mainInfoRef.value.getList()
}
// 应付费
const tofee = () => {
  payRef.value.open = true
}
// 清关费用详情

// 装柜
const handleCabinet = () => {
  cabRef.value.open = true
}
// 装柜修改
const handleEdit = () => {
  zgEditRef.value.open = true
  zgEditRef.value.idss = JSON.parse(JSON.stringify(idss.value))
  zgEditRef.value.transportTypes = JSON.parse(JSON.stringify(transportTypes.value))
  zgEditRef.value.cab = JSON.parse(JSON.stringify(cabs.value))
  zgEditRef.value.initdata()
}
// 签出
const query5 = ref({
  pageSize: 10,
  pageNum: 1,
  cabinetNo: '',
  transportType: '',
  id: '',
})
const handleAddTotalOrder = () => {
  const ids = JSON.parse(JSON.stringify(idss.value))
  const ts = JSON.parse(JSON.stringify(transportTypes.value))
  const cb = JSON.parse(JSON.stringify(cabs.value))
  query5.value.id = ids[0]
  query5.value.cabinetNo = cb[0]
  query5.value.transportType = ts[0] 
  open.value = true
  title.value = '签出'
}

const cancle5 = () => {
  open5.value = false
}
const submitForm = () => {
  const data = query5.value
  $validateForm(form1.value, () => {
    open5.value = true
    loading5.value = true
    console.log(1111)
    
    queryMergeLoadingOrderInfo(data).then(res => {
      if (res.code == 200) {
        tableList1.value = res.data
        loading5.value = false
      }
    }).catch(() => {
      loading5.value = false
    })
  })
}
const sumit5 = () => {
  form.value.id = query5.value.id
  form.value.transportType = Number(query5.value.transportType)
  form.value.cabinetNo = query5.value.cabinetNo
  const data = form.value
  btnloading.value = true
  ladingOut(data).then(res => {
    if (res.code == 200) {
      ElMessage.success('签出成功')
      open5.value = false
      btnloading.value = false
      editCancel()
      initData()
    } else {
      ElMessage.error(res.msg)
      btnloading.value = false
    }
  }).catch(() => {
    btnloading.value = false
  })
}
const editCancel = () => {
  open.value = false
  proxy.$refs.form1.resetFields()
}
// 撤销签出
const handleRevoke = () => {
  const loadNo = JSON.parse(JSON.stringify(loadNos.value))
  const status = JSON.parse(JSON.stringify(statuss.value))
  const auditStatus = JSON.parse(JSON.stringify(auditStatuss.value))

  console.log(status[0], auditStatus[0], loadNo[0])
 
  if (status[0] !== '4') {
    revokeForm.value.ladingNo = loadNo
    open1.value = true
  } else {
    ElMessageBox.alert('已排柜或审核中的不能操作')
  }
}
const revokeSubmit = () => {
  
}
const cancle1 = () => {
  open1.value = false
  proxy.$refs.form2.resetFields()
}
const initData = () => {
  mainConfig.value.getList()
}
// 删除装柜
const handleDelete = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  const ids = JSON.parse(JSON.stringify(idss.value))
  const id = ids[0]
  if (status[0] == '4') {
    ElMessageBox.confirm('敏感操作！是否继续？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      delPackage(id).then(res => {
        if (res.code == 200) {
          ElMessage.success('删除成功')
          initData()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  } else {
    ElMessageBox.alert('只有已装柜的才能操作')
  }
}
const orderStatus = ref(undefined)
// 国内查验
const handleInspection = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    open2.value = true
    title2.value = '国内查验'
    orderStatus.value = 12
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 国内报关
const handleDeclaration = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    open2.value = true
    title2.value = '国内报关'
    orderStatus.value = 18
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 国内已放行
const handleDomestically = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    open2.value = true
    title2.value = '国内已放行'
    orderStatus.value = 15
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 国外查验
const handleForeignInspection = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    open2.value = true
    title2.value = '国外查验'
    orderStatus.value = 13
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 已到港
const handleArrived = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    open2.value = true
    title2.value = '已到港'
    orderStatus.value = 17
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 国外清关
const customsClearances = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    open2.value = true
    title2.value = '国外清关'
    orderStatus.value = 18
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 国外清关已放行
const handleCustomsClearance = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    open2.value = true
    title2.value = '国外清关已放行'
    orderStatus.value = 6
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
const cancle2 = () => {
  open2.value = false
  proxy.$refs.queryForm.resetFields()
}
const querys = ref({
  serviceSimpleName: 'AINIEN',
  sysOrderOperation: {},
  deliveryTotalNo: undefined,
})
const sumit2 = () => {
  const ids = JSON.parse(JSON.stringify(idss.value))
  const loadNo = JSON.parse(JSON.stringify(loadNos.value))
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value))
  const transportT = JSON.parse(JSON.stringify(transportTypes.value))
  $validateForm(queryForm.value, () => {
    const queryParams = JSON.parse(JSON.stringify(querys.value))
    queryParams.transportType = transportT[0]
    queryParams.idList = ids
    queryParams.orderNoList = orderNoList
    queryParams.ladingNoList = loadNo
    queryParams.executorName = userName
    queryParams.sysOrderOperation.operationTime = form3.value.operationTime
    queryParams.sysOrderOperation.operationUser = userName
    queryParams.sysOrderOperation.orderStatus = proxy.orderStatus
    sentRequest(queryParams).then(res => {
      if (res.code == 200) {
        open2.value = false
        proxy.$refs.queryForm.resetFields()
        mainConfig.value.getList()
        ElMessage.success(res.msg)
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const sentRequest = async (params) => {
  let Res
  switch (title2.value) {
    // case "签出":
    //   Res = await ladingOut(params);
    //   break;
    case '国内报关':
      Res = await domesticDeclaration(params)
      break
    case '国内查验':
      Res = await domesticInspection(params)
      break
    case '国内已放行':
      Res = await domesticDomestically(params)
      break
    case '已到港':
      Res = await saveOrderArrivedTrack(params)
      break
    case '国外清关':
      Res = await customsClearance(params)
      break
    case '国外查验':
      Res = await foreignInspection(params)
      break
    case '国外清关已放行':
      Res = await abroadClearanceReleased(params)
      break
        // default:
        //   Res = await ladingOut(params);
        //   break;
  }
  return Res
}
const popoverForm = ref({
  type: undefined,
  title: undefined,
  date: undefined,
  data: {},
  
})

// 已提柜
const handleCarryCabinet = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  const ids = JSON.parse(JSON.stringify(idss.value))
  const loadNo = JSON.parse(JSON.stringify(loadNos.value))
  const orderNoListss = JSON.parse(JSON.stringify(orderNoLists.value))
  const datas = {
    idList: ids,
    orderNoList: orderNoListss,
    ladingNoList: loadNo,
  }
  if (status[0] !== '4') {
    open4.value = true
    title4.value = '已提柜时间'
    orderStatus.value = 17
    popoverForm.value = {
      type: '已提柜',
      data: datas,
      date: '',
      title: '已提柜时间',
    }
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 已提交UPS
const handleUps = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  const ids = JSON.parse(JSON.stringify(idss.value))
  const loadNo = JSON.parse(JSON.stringify(loadNos.value))
  const orderNoListss = JSON.parse(JSON.stringify(orderNoLists.value))
  const datas = {
    idList: ids,
    orderNoList: orderNoListss,
    ladingNoList: loadNo,
  }
  if (status[0] !== '4') {
    open4.value = true
    title4.value = 'ups'
    orderStatus.value = 19
    popoverForm.value = {
      type: 'ups',
      data: datas,
      date: '',
      title: '已提交ups时间',
    }
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 已提交海外仓
const handleOverseas = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  const ids = JSON.parse(JSON.stringify(idss.value))
  const loadNo = JSON.parse(JSON.stringify(loadNos.value))
  const orderNoListss = JSON.parse(JSON.stringify(orderNoLists.value))
  const datas = {
    idList: ids,
    orderNoList: orderNoListss,
    ladingNoList: loadNo,
  }
  if (status[0] !== '4') {
    open4.value = true
    title4.value = '已提交海外仓'
    orderStatus.value = 20
    popoverForm.value = {
      type: '已提交海外仓',
      data: datas,
      date: '',
      title: '已提交海外仓',
    }
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
const btnLoading4 = ref(false)
const cancle4 = () => {
  open4.value = false
  proxy.$refs.popoverForms.resetFields()
}
const sumit4 = () => {
  $validateForm(popoverForms.value, () => {
    const data = popoverForm.value.data
    data.sysOrderOperation = {
      operationUser: userName,
      orderStatus: proxy.orderStatus,
      operationTime: popoverForm.value.date,
    }
    if (popoverForm.value.type == 'ups') {
      data.upsSubmittedTime = popoverForm.value.date
      common(submitUps, data)
    } else if (popoverForm.value.type === '已提柜') {
      data.deliveredCabinetTime = popoverForm.value.date
      common(carryCabinet, data)
    } else if (popoverForm.value.type === '已提交海外仓') {
      data.submittedOverseasTime = popoverForm.value.date
      common(submitOverseas, data)
    }
  })
}
const common = (api, data) => {
  api(data)
  .then(res => {
    if (res.code == 200) {
      open4.value = false   
      ElMessage.success('操作成功')
      btnLoading4.value = false
      mainConfig.value.getList()
      proxy.$refs.popoverForms.resetFields()
    } else {
      btnLoading4.value = false
    }
  })
  .catch(err => {
    console.log(err)
    btnLoading4.value = false
  })
}

// 导出清关资料(中)
const handleExportZh = () => {
  const data = {
    pageNum: 1,
    pageSize: 10,
    transportType: queryParams.value.transportType,
    ladingNoList: loadNos.value,
  }
  $download('order/deliveryMerge/exportMergeOrder/false', data, `清关资料(中)${ new Date().getTime() }.xlsx`)
}

// 导出清关资料(英)
const handleExportEn = () => {
  const data = {
    pageNum: 1,
    pageSize: 10,
    transportType: queryParams.value.transportType,
    ladingNoList: loadNos.value,
  }
  $download('order/deliveryMerge/exportMergeOrder/true', data, `清关资料(英${ new Date().getTime() }.xlsx`)
}
// 导出出库明细
const handleOutputExport = () => {
  const data = {
    pageNum: 1,
    pageSize: 10,
    transportType: queryParams.value.transportType,
    ladingNo: loadNos.value.toString(),
  }
  $download('order/deliveryMerge/export', data, `出库明细${ new Date().getTime() }.xlsx`)
}
// 导出空海派登记表
const handleOutputExport2 = () => {
  const data = {
    pageNum: 1,
    pageSize: 10,
    transportType: queryParams.value.transportType,
    ladingNo: loadNos.value.toString(),
  }
  $download('order/deliveryMerge/shippingRegistrationForm/export', data, `空海派登记表${ new Date().getTime() }.xlsx`)
}
// 导出空派清关资料
// const handleExportQG = () => {
  
// }
const idss = ref([])
const loadNos = ref([])
const statuss = ref([])
const auditStatuss = ref([])
const orderNoLists = ref([])
const transportTypes = ref([])
const cabs = ref([])
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  console.log(rows)
  
  statuss.value = rows.map((item) => item.status)
  auditStatuss.value = rows.map((item) => item.auditStatus)
  idss.value = rows.map((item) => item.id)
  loadNos.value = rows.map((item) => item.ladingNo)
  transportTypes.value = rows.map((item) => item.transportType)
  cabs.value = rows.map((item) => item.cabinetNo)
  single.value = rows.length != 1 
  multiple.value = !rows.length
  orderNoLists.value = rows.map((item) => item.orderNo)
  multiple2.value = !rows.length || rows.some(el => el.status == 6)
  single2.value = rows.some(el => el.transportType == 2)
}

const config = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '客户订单号',
            prop: 'waybillNo',
            option: {
              placeholder: '请输入客户订单号',
              type: 'textarea',
            },
          },
          {
            label: '提单号',
            prop: 'ladingNo',
            option: {
              placeholder: '请输入提单号',
              type: 'textarea',
            },
          },
          {
            label: '虚拟柜号',
            prop: 'cabinetNo',
            option: {
              placeholder: '请输入虚拟柜号',
              type: 'textarea',
            },
          },
          {
            label: '系统订单号',
            prop: 'orderNo',
          },
          {
            type: 'select',
            label: '服务商',
            prop: 'providerServiceCode',
            option: {
              dictInfo: { dict: DictDirection.服务商 },
            },
          },
          {
            label: '航次/航班号',
            prop: 'voyageNo',
          },
          {
            label: '船公司',
            prop: 'transportName',
          },
          {
            label: '箱号',
            prop: 'caseNo',
          },
          {
            type: 'date-picker',
            label: '开船日',
            prop: 'datetimePicker',
            option: {
              type: 'datetime',
            },
          },
          {
            type: 'date-picker',
            label: '装柜日',
            prop: 'datetimePicker',
            option: {
              type: 'datetime',
            },
          },
          {
            type: 'select',
            label: '订单状态',
            prop: 'status',
            option: {
              dictInfo: { dict: DictDirection.包裹状态 },
            },
          },
          {
            type: 'select',
            label: '运输类型',
            prop: 'transportType',
            option: {
              dictInfo: { dict: DictDirection.运输类型 },
            },
          },
        ],
        queryParams: queryParams.value,
        formOption: {},
      },
      btns: [
        {
          title: '装柜',
          type: 'primary',
          onClick: handleCabinet,
        },
        {
          title: '装柜修改',
          onClick: handleEdit,
          disabled: single.value,
          type: 'primary',
        },
        {
          title: '签出',
          onClick: handleAddTotalOrder,
          type: 'primary',
          disabled: single.value,
        },
        {
          title: '撤销签出',
          onClick: handleRevoke,
          disabled: single.value,
          type: 'info',
        },
        {
          title: '删除装柜',
          onClick: handleDelete,
          disabled: single.value,
          type: 'danger',
        },
        {
          title: '国内查验',
          onClick: handleInspection,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '国内报关',
          onClick: handleDeclaration,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '国内已放行',
          onClick: handleDomestically,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '国外查验',
          onClick: handleForeignInspection,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '国外清关',
          onClick: customsClearances,
          type: 'primary',
          disabled: multiple2.value,
        },
        {
          title: '国外清关已放行',
          onClick: handleCustomsClearance,
          type: 'primary',
          disabled: single.value,
        },
        {
          title: '已到港',
          onClick: handleArrived,
          type: 'success',
          disabled: multiple2.value,
        },
        {
          title: '已提柜',
          onClick: handleCarryCabinet,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '已提交UPS',
          onClick: handleUps,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '已提交海外仓',
          onClick: handleOverseas,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '导出清关资料(中)',
          onClick: handleExportZh,
          type: 'warning',
          disabled: multiple.value,
        },
        {
          title: '导出清关资料(英)',
          onClick: handleExportEn,
          type: 'primary',
          disabled: multiple.value,
        },
        {
          title: '导出出库明细',
          onClick: handleOutputExport,
          type: 'success',
          disabled: single.value,
        },
        {
          title: '导出空海派登记表',
          onClick: handleOutputExport2,
          type: 'primary',
          disabled: multiple.value,
        },
        // {
        //   title: '导出空派清关资料',
        //   onClick: handleExportQG,
        //   type: 'primary',
        //   disabled: single2.value,
        // },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
          {
            label: '提单号',
            prop: 'ladingNo',
            align: 'center',
            width: '120',
          },
          { label: '虚拟柜号', align: 'center', prop: 'cabinetNo', width: '120' },
          { label: '运输类型',
            align: 'center',
            prop: 'transportType',
            autoFormatter: {
              dict: DictDirection.运输类型,
              rowKey: 'transportType',
            } },
          { label: '服务商简称', align: 'center', prop: 'providerServiceCode' },
          { label: '服务渠道',
            align: 'center',
            prop: 'serviceChannelCode',
            autoFormatter: {
              dict: DictDirection.服务渠道,
              rowKey: 'serviceChannelCode',
            } },
          { label: '状态',
            align: 'center',
            width: '100',
            prop: 'status',
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'status',
            } },
          { label: '审核状态', align: 'center', prop: 'approvalStatus' },
          { label: '船名航次', align: 'center', prop: 'voyageNo' },
          { label: '目的港', align: 'center', prop: 'portDestination' },
          { label: '封号', align: 'center', prop: 'sealNo' },
          { label: '箱号', align: 'center', prop: 'caseNo' },
          { label: '船/航空公司', align: 'center', prop: 'transportName' },
          { label: '装柜地点', align: 'center', prop: 'loadingLocation' },
          { label: '创建日期', align: 'center', prop: 'createDate' },
          { label: '总实重', align: 'center', prop: 'totalSolidWeight' },
          { label: '总材积重（方）', align: 'center', prop: 'totalVolumeWeight' },
          { label: '总件数', align: 'center', prop: 'totalPiece' },
          { label: '报关行', align: 'center', prop: 'customsLine' },
          { label: '拖车行', align: 'center', prop: 'trailerLine' },
          { label: '预计起飞日', align: 'center', prop: 'expectedSailingDate', width: '150' },
          // { :label:queryParams.transportType == 2 ? '预计起飞日' : '预计开船日', prop: 'expectedSailingDate' },
          { label: '预计到达', align: 'center', prop: 'expectedArrivalDate', width: '150' },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            width: '300',
            render(h, params) {
              const buttons = [
                {
                  title: '应付费',
                  clickFun: tofee,
                },
                {
                  title: '查看详情',
                  clickFun: handleRouterPush,
                },
              ]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  // icon: el.icon,
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: mergeOutList,
      customKey: 'express/mainBusiness/oceanShipping/outputWarehouseManagement',
    }
  },
  set(v) {
    return v
  },
})
</script>

<style lang="less" scoped>
.ypg_title {
  float: right;
  span:first-child {
    color: #fcaf17;
  }
  span:last-child {
    color: red;
  }
}
.dialog-footer {
  text-align: right;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
